<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="3" :xs="24" v-if="isEBUser">
        <div class="head-container" v-show="showRegion">
          <el-tree
              :data="regionOptions"
              :props="defaultProps"
              :expand-on-click-node="false"
              :filter-node-method="filterNode"
              ref="regionTreeRef"
              node-key="id"
              default-expand-all
              highlight-current
              accordion
              v-loading="loading"
              @node-click="handleRegionNodeClick"
          />
        </div>
        <div class="head-container" v-show="showSchool">
          <el-button
              v-show="showSchool"
              type="primary"
              icon="Back"
              circle
              plain
              @click="handleBack"
          />
          <el-tree
              :data="schoolList"
              :props="{ label: 'schoolName', value: 'schoolId' }"
              :expand-on-click-node="false"
              :filter-node-method="filterNode"
              ref="schoolTreeRef"
              node-key="id"
              default-expand-all
              highlight-current
              accordion
              v-loading="loading"
              @node-click="handleSchoolNodeClick"
          />
        </div>
      </el-col>
      <el-col :span="mainColSpan" :xs="24">
        <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="类型" prop="typeId">
            <el-select v-model="queryParams.typeId" placeholder="请选择类型" clearable style="width: 180px">
              <el-option
                  v-for="type in typeList"
                  :key="type.typeId"
                  :label="type.typeName"
                  :value="type.typeId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="状态" prop="issueStatus">
            <el-select v-model="queryParams.issueStatus" placeholder="请选择状态" clearable style="width: 180px">
              <el-option
                  v-for="dict in sys_issue_status"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
        <el-row :gutter="10" class="mb8">
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" />
        </el-row>

        <el-table v-loading="loading" border :data="issueList">
          <el-table-column label="序号" type="index" width="55" />
          <el-table-column label="用户名" align="center" prop="userName" />
          <el-table-column label="手机号" align="center" prop="phoneNum" width="120" />
          <el-table-column label="类型" align="center" prop="typeName" />
          <el-table-column label="标题" align="center" prop="issueTitle" width="200" />
          <el-table-column label="所属学校" align="center" prop="schoolName" />
          <el-table-column label="图片列表" align="center" prop="issueImages" width="120">
            <template #default="scope">
              <ImagePreviewWithMore
                  :src="scope.row.issueImages"
                  :image-width="100"
                  :image-height="100"
                  width="50px"
                  v-if="scope.row.issueImages"
              />
            </template>
          </el-table-column>
          <el-table-column label="处理状态" align="center" prop="issueStatus">
            <template #default="scope">
              <dict-tag :options="sys_issue_status" :value="scope.row.issueStatus" />
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="200px">
            <template #default="scope">
              <el-button
                  link
                  type="primary"
                  v-if="scope.row.issueStatus === 0"
                  icon="EditPen"
                  @click="handleFeedBack(scope.row)"
                  v-hasPermi="['system:feedback:add']"
              >
                处理
              </el-button>
              <el-button
                  link
                  type="primary"
                  icon="Paperclip"
                  @click="handleShowFeedBack(scope.row)"
                  v-hasPermi="['system:feedback:query']"
              >
                详情
              </el-button>
              <el-button
                  link
                  type="primary"
                  icon="Delete"
                  @click="handleDelete(scope.row)"
                  v-hasPermi="['system:issue:remove']"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
            v-show="total > 0"
            :total="total"
            v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize"
            @pagination="getList"
        />
      </el-col>
    </el-row>

    <el-dialog :title="previewTitle" v-model="previewDialogVisible" width="500px" append-to-body>
      <el-form label-width="80px">
        <div v-html="selectedIssue.issueContent"></div>
      </el-form>
      <template #footer>
        <el-button @click="cancel">关闭</el-button>
      </template>
    </el-dialog>

    <el-dialog :title="title" v-model="open" width="1000px" append-to-body>
      <el-form :model="form" :rules="rules" ref="formRef" label-width="50px">
        <el-descriptions title="基本信息" :column="2" border class="margin-top">
          <el-descriptions-item>
            <template #label>
              <div class="cell-item">
                <el-icon style="margin: 6px">
                  <User />
                </el-icon>
                用户名
              </div>
            </template>
            {{ form.userName }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label>
              <div class="cell-item">
                <el-icon style="margin: 6px">
                  <Iphone />
                </el-icon>
                电话号
              </div>
            </template>
            {{ form.phoneNum }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label>
              <div class="cell-item">
                <el-icon style="margin: 6px">
                  <tickets />
                </el-icon>
                类型
              </div>
            </template>
            <el-tag>{{ form.typeName }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label>
              <div class="cell-item">
                <el-icon style="margin: 6px">
                  <school />
                </el-icon>
                学校
              </div>
            </template>
            {{ form.schoolName }}
          </el-descriptions-item>
        </el-descriptions>
        <el-divider />
        <el-descriptions title="内容" :column="1" border class="margin-top">
          <el-descriptions-item label="标题">{{ form.issueTitle }}</el-descriptions-item>
          <el-descriptions-item label="内容">
            <el-input v-model="form.issueContent" type="textarea" :rows="5" readonly />
          </el-descriptions-item>
          <el-descriptions-item label="图片列表">
            <ImageList
                :images="form.issueImages"
                :image-width="100"
                :image-height="100"
                v-if="form.issueImages && form.issueImages.length > 0"
            />
          </el-descriptions-item>
        </el-descriptions>
      </el-form>
      <el-divider v-if="form.issueStatus === 1" />
      <el-descriptions title="处理信息" :column="1" border class="margin-top" v-if="form.issueStatus === 1">
        <el-descriptions-item label="处理内容">{{ issueFeedBack.feedbackContent || '无' }}</el-descriptions-item>
        <el-descriptions-item label="相关图片">
          <ImageList
              :images="issueFeedBack.feedbackImages"
              :image-width="100"
              :image-height="100"
              v-if="issueFeedBack.feedbackImages && issueFeedBack.feedbackImages.length > 0"
          />
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, watch, toRefs, getCurrentInstance } from 'vue';
import { useRouter } from 'vue-router';
import { listIssue, getIssue, delIssue, addIssue, updateIssue, getFeedBackByIssueId } from '@/api/system/issue';
import { listSchool } from '@/api/system/school';
import { listRegionTree } from '@/api/system/region';
import { listType } from '@/api/system/type';
import { getInfo } from '@/api/login';
import ImagePreviewWithMore from '@/components/ImagePreviewWithMore/ImagePreviewWithMore.vue';
import ImageList from '@/components/ImageList/index.vue';
import DictTag from '@/components/DictTag/index.vue';
import { User, Iphone, Tickets, School } from '@element-plus/icons-vue';
import { computed } from 'vue';

const { proxy } = getCurrentInstance();
const router = useRouter();
const mainColSpan = computed(() => (isEBUser.value ? 21 : 24));

// 数据定义
const isEBUser = ref(false);
const regionName = ref('');
const issueList = ref([]);
const schoolList = ref([]);
const typeList = ref([]);
const regionOptions = ref([]);
const showRegion = ref(true);
const showSchool = ref(false);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref('');
const userRole = ref('');
const previewTitle = ref('');
const selectedIssue = reactive({
  issueTitle: '',
  issueContent: '',
  schoolId: '',
});
const previewDialogVisible = ref(false);
const { sys_issue_status } = proxy.useDict('sys_issue_status');
const issueFeedBack = reactive({
  feedbackContent: '',
  feedbackImages: '',
  issueId: '',
});
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userId: null,
    issueTitle: null,
    issueContent: null,
    schoolId: null,
    issueImages: null,
    issueStatus: null,
  },
  rules: {},
});

const { queryParams, form, rules } = toRefs(data);

// 方法定义
function filterNode(value, data) {
  if (!value) return true;
  return data.label.indexOf(value) !== -1;
}

function getList() {
  loading.value = true;
  listIssue(queryParams.value)
      .then((response) => {
        issueList.value = response.rows;
        total.value = response.total;
      })
      .catch((error) => {
        console.error('获取 issue 列表失败:', error);
        proxy.$modal.msgError('获取列表失败，请稍后重试');
      })
      .finally(() => {
        loading.value = false;
      });
}

function getRegionTree() {
  listRegionTree().then((response) => {
    regionOptions.value = response.data;
  });
}

function cancel() {
  open.value = false;
  previewDialogVisible.value = false;
  reset();
}

function reset() {
  form.value = {
    issueId: null,
    userId: null,
    issueTitle: null,
    issueContent: null,
    schoolId: null,
    issueImages: null,
    issueStatus: null,
    phoneNum: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    delFlag: null,
  };
  proxy.resetForm('issueRef');
}

function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

function resetQuery() {
  proxy.resetForm('queryRef');
  queryParams.value.pageNum = 1;
  queryParams.value.schoolId = null;
  showRegion.value = true;
  showSchool.value = false;
  handleQuery();
}

function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.issueId);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

function handleAdd() {
  reset();
  open.value = true;
  title.value = '添加问题信息';
}

function handleUpdate(row) {
  reset();
  const _issueId = row.issueId || ids.value;
  getIssue(_issueId).then((response) => {
    form.value = response.data;
    open.value = true;
    title.value = '修改问题信息';
  });
}

function submitForm() {
  proxy.$refs['issueRef'].validate((valid) => {
    if (valid) {
      if (form.value.issueId != null) {
        updateIssue(form.value).then(() => {
          proxy.$modal.msgSuccess('修改成功');
          open.value = false;
          getList();
        });
      } else {
        addIssue(form.value).then(() => {
          proxy.$modal.msgSuccess('新增成功');
          open.value = false;
          getList();
        });
      }
    }
  });
}

function handleDelete(row) {
  const _issueIds = row.issueId || ids.value;
  if (!_issueIds || _issueIds.length === 0) {
    proxy.$modal.msgWarning('请选择要删除的数据');
    return;
  }
  proxy.$modal
      .confirm('是否确认删除问题信息编号为"' + _issueIds + '"的数据项？')
      .then(() => {
        return delIssue(_issueIds); // 返回 Promise 以便链式调用
      })
      .then(() => {
        getList();
        proxy.$modal.msgSuccess('删除成功');
      })
      .catch((error) => {
        console.error('删除失败:', error);
        proxy.$modal.msgError('删除失败，请稍后重试');
      });
}

function getSchoolList(id) {
  loading.value = true;
  queryParams.value.regionId = id;
  listSchool(queryParams.value)
      .then((response) => {
        schoolList.value = response.rows;
        total.value = response.total;
      })
      .finally(() => {
        loading.value = false;
      });
}

function handleFeedBack(row) {
  const issueId = row.issueId;
  router.push({
    name: 'FeedBack',
    params: { issueId },
  });
}

function handleShowFeedBack(row) {
  const _issueId = row.issueId;
  getIssue(_issueId)
      .then((response) => {
        form.value = response.data;
        open.value = true;
        title.value = '';
      })
      .catch((error) => {
        console.error('获取 issue 详情失败:', error);
        proxy.$modal.msgError('获取详情失败');
      });
  if (row.issueStatus === 1) {
    getFeedBackByIssueId(_issueId)
        .then((response) => {
          Object.assign(issueFeedBack, response.data);
        })
        .catch((error) => {
          console.error('获取反馈信息失败:', error);
          proxy.$modal.msgError('获取反馈信息失败');
        });
  }
}

function handleRegionNodeClick(data) {
  if (!data) return;
  showRegion.value = false;
  showSchool.value = true;
  getSchoolList(data.id);
}

function handleSchoolNodeClick(data) {
  if (!data) return;
  queryParams.value.schoolId = data.schoolId;
  getList();
}

function handleBack() {
  showSchool.value = false;
  showRegion.value = true;
}

function getUserInfo() {
  getInfo().then((res) => {
    if (res.roles && res.roles.length > 0) {
      userRole.value = res.roles[0] || '';
      if (userRole.value === 'admin' || userRole.value === 'education') {
        isEBUser.value = true;
      }
    }
  });
}

function getTypeList() {
  listType(queryParams.value).then((response) => {
    typeList.value = response.rows;
    total.value = response.total;
  });
}

watch(
    () => router.currentRoute.value.fullPath,
    () => {
      getList();
    },
    { immediate: true }
);

// 初始化
getUserInfo();
getList();
getRegionTree();
getTypeList();
</script>